package com.base.project.deeplinks

import android.app.Activity
import android.content.Intent
import android.net.Uri
import com.android.installreferrer.api.InstallReferrerClient
import com.android.installreferrer.api.InstallReferrerStateListener
import com.blankj.utilcode.util.LogUtils
import com.base.project.Constants
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume


/**
 * Created by Orange on 2022/12/4 17:50.
 * Play Install Referrer https://developer.android.com/google/play/installreferrer/library
 */
class GoogleTask : Task {

    private var mReferrerClient: InstallReferrerClient? = null
    private var urlHead = "http://test.com?" // 添加到referrerUrl 方便解析

    override suspend fun asyncGetUrl(activity: Activity, intent: Intent?) =
        suspendCancellableCoroutine { continuation ->
            //只做一次解析
            if (Constants.googleReferrer) {

                mReferrerClient = InstallReferrerClient.newBuilder(activity).build()
                mReferrerClient?.startConnection(object : InstallReferrerStateListener {

                    override fun onInstallReferrerSetupFinished(responseCode: Int) {
                        try {
                            if (responseCode == InstallReferrerClient.InstallReferrerResponse.OK) {
                                mReferrerClient?.run {

                                    val referrerUrl = installReferrer?.installReferrer ?: ""

                                    //数据格式  page_type=23&r_id=10809&vid=17163&timestamp=1625815462
                                    LogUtils.d("onInstallReferrerSetupFinished: referrerUrl = $referrerUrl")

                                    //解析referrerUrl
                                    if (referrerUrl.isNotEmpty()) {
                                        val uri = Uri.parse(urlHead + referrerUrl)
                                        //当解析到预设的参数 就不在解析了
                                        val rId = uri.getQueryParameter("r_id") ?: ""
                                        if (rId.isNotEmpty()) {
                                            Constants.googleReferrer = true
                                            continuation.resume(
                                                LinkData(
                                                    uri = uri,
                                                    tag = "Google Referrer"
                                                )
                                            )
                                        }
                                    }
                                }
                                end()
                            } else {
                                LogUtils.d("onInstallReferrerSetupFinished: $responseCode")
                            }
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }

                    override fun onInstallReferrerServiceDisconnected() {
                        // Try to restart the connection on the next request to
                        // Google Play by calling the startConnection() method.
                        LogUtils.d("onInstallReferrerServiceDisconnected: ")
                    }
                })

            } else {
                LogUtils.d("Play Install Referrer 只做一次解析")
            }

            continuation.invokeOnCancellation {
                // 协程被取消
                end()
            }
        }

    private fun end() {
        mReferrerClient?.run {
            if (isReady) {
                endConnection()
            }
        }
    }
}